package com.kingdee.eas.basedata.org.app;

import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.bos.dao.IObjectPK;
import com.kingdee.bos.dao.IObjectValue;
import com.kingdee.bos.dao.ormapping.ObjectUuidPK;
import com.kingdee.bos.metadata.entity.SelectorItemCollection;
import com.kingdee.eas.basedata.org.AdminOrgUnitInfo;
import com.kingdee.eas.basedata.org.JobInfo;
import com.kingdee.eas.basedata.org.PositionFactory;
import com.kingdee.eas.basedata.org.PositionInfo;
import com.kingdee.eas.basedata.org.PositionMemberInfo;
import com.kingdee.eas.basedata.person.PersonFactory;
import com.kingdee.eas.basedata.person.PersonInfo;
import com.kingdee.eas.common.EASBizException;
import com.kingdee.eas.dynbusiness.util.DBUtil;

public class PositionMemberControllerBeanEx extends PositionMemberControllerBean {

	@Override
	protected IObjectPK _addnew(Context ctx, IObjectValue model) throws BOSException, EASBizException {
		PositionMemberInfo info = (PositionMemberInfo) model;
		IObjectPK pk = super._addnew(ctx, model);
		if (info.isIsPrimary()) {

			PositionInfo positionInfo = PositionFactory.getLocalInstance(ctx).getPositionInfo(
					new ObjectUuidPK(info.getPosition().getId()));

			AdminOrgUnitInfo orgUnitInfo = positionInfo.getAdminOrgUnit();
			JobInfo jobInfo = positionInfo.getJob();
			PersonInfo personInfo = info.getPerson();

			personInfo.setDept(orgUnitInfo);
			personInfo.setDuty(jobInfo);
			PersonFactory.getLocalInstance(ctx).updatePartial(personInfo, getSelectorItemCollection());
		}
		return pk;
	}

	@Override
	protected void _delete(Context ctx, IObjectPK pk) throws BOSException, EASBizException {
		PositionMemberInfo oldInfo = getPositionMemberInfo(ctx, pk);
		if (oldInfo.isIsPrimary()) {
			PersonInfo personInfo = oldInfo.getPerson();

			personInfo.setDept(null);
			personInfo.setDuty(null);
			PersonFactory.getLocalInstance(ctx).updatePartial(personInfo, getSelectorItemCollection());
		}
		super._delete(ctx, pk);
	}

	@Override
	protected void _update(Context ctx, IObjectPK pk, IObjectValue model) throws BOSException, EASBizException {
		PositionMemberInfo info = (PositionMemberInfo) model;
		super._update(ctx, pk, model);
		if (info.isIsPrimary()) {
			AdminOrgUnitInfo orgUnitInfo = info.getPosition().getAdminOrgUnit();
			JobInfo jobInfo = info.getPosition().getJob();
			PersonInfo personInfo = info.getPerson();

			personInfo.setDept(orgUnitInfo);
			personInfo.setDuty(jobInfo);
			PersonFactory.getLocalInstance(ctx).updatePartial(personInfo, getSelectorItemCollection());
		}
	}

	private SelectorItemCollection getSelectorItemCollection() {
		SelectorItemCollection selectors = new SelectorItemCollection();
		selectors.add("dept");
		selectors.add("duty");
		return selectors;
	}
}
